#include <string.h>
#include <stdio.h>
#include <iostream>
#include "hse_common.h"
#include "tokenizer.h"

namespace hse {
using std::string;
using std::vector;

#define hse_tolower(x) (( (x) >= 'A' && (x) <= 'Z' ) ?  ((x) + 'a' - 'A') : (x) )

int string_term_find(string& src, string& lowercased_find, int npos) {
	if (lowercased_find.size() > src.size() - npos)
		return -1;
	for(int i = npos; i < src.size() - lowercased_find.size(); ++i) {
		if ((hse_tolower(src[i]) == lowercased_find[0]) 
			&& (i == 0 || Tokenizer::IsSpliter(src[i-1]))) 
		{
			int j;
			for (j = 1; j < lowercased_find.size(); ++j) {
				if (hse_tolower(src[i + j]) != lowercased_find[j])
					break;
			}
			if (j == lowercased_find.size() && (i + j == src.size() || Tokenizer::IsSpliter(src[i + j])))
				return i;
		}
	}
	return -1;
}

string string_term_em(string& src, vector<string>& terms) {
	int npos = 0, t = -1, lpos = 0, j, mt, mj;
	string r;
	while(npos != -1) {
		mt = -1;
		for(j = 0; j < terms.size(); ++j) {
			if ((t = string_term_find(src, terms[j], npos)) != -1 && (t < mt || mt == -1)) {
				mt = t;
				mj = j;
			}
		}
		npos = mt;
		if (npos != -1) {
			r.append(src, lpos, npos - lpos);
			r.append("<em>");
			r.append(src, npos, terms[mj].size());
			r.append("</em>");
		}
		if (npos >= 0) {
			lpos = npos + terms[mj].size();
			npos++;
		}
	}
	if (lpos != src.size() - 1) {
		r.append(src, lpos, src.size() - lpos);
	}
	return r;
}



}